package com.book.web;

import com.book.pojo.User;
import com.book.service.UserService;
import com.book.service.impl.UserServiceImpl;
import com.book.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class UserServlet extends BaseServlet {
    private UserService userService=new UserServiceImpl();

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取请求的参数
        String username = req.getParameter("username");
        //调用userService.existsUsername
        boolean existUsername = userService.existUsername(username);
        //把返回的结果封装成为map对象
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername",existUsername);
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);


    }
    /**
     * 处理注销请求的代码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //销毁session中用户登录的信息，或者直接销毁session
        req.getSession().invalidate();
        //重定向到首页
        resp.sendRedirect(req.getContextPath());
    }
    /**
     * 处理登录请求的代码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //1.获取登录所需参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.调用usrService.Login()处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        //如果等于NUll说明登录失败
        if (loginUser == null) {
            //把错误信息，和回显的表单项信息，保存到Request域中
            req.setAttribute("msg","用户或密码错误！");
            req.setAttribute("username",username);
            //跳转回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else {
            //登录成功，跳转登录成功页面
            //保存用户登录的信息到session域中
            req.getSession().setAttribute("user",loginUser);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }

    /**
     * 处理注册请求的代码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取Session中的验证码
        String token=(String) req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        //删除Session中的验证码

        //获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String email=req.getParameter("email");
        String code=req.getParameter("code");//验证码
        System.out.println(userService.existUsername("admin2"));
        User user= WebUtils.copyParamBean(req.getParameterMap(),new User());//调用工具类实现注入[状态：功能完成，但未使用]
        //2.检查验证码是否正确
        if(token!=null&&token.equalsIgnoreCase(code)){
            //3检查用户名是否可用
            if (userService.existUsername(username)) {
                //不可用
                //要回显的信息放到Request域中
                req.setAttribute("msg","用户名已存在!");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                System.out.println("用户名【"+username+"】已存在！");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);//不得已转发到/book中默认访问的index.jpg下
            }else {
                //可用
                userService.registUser(new User(null,username,password,email));//调用数据库保存数据
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);//注册成功页面
            }
        }else {
            //要回显的信息放到Request域中
            req.setAttribute("msg","验证码错误！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码错误，请求转发！");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);//回到注册页面
        }
    }



}

